package com.mfhcd.facepay.utils;

import java.util.Comparator;
import java.util.concurrent.Executor;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by zhanghs on 2017/1/10.
 */

public class ThreadPoolUtil {
    /**
     * 获取当前的cpu核心数
     */
    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    /**
     * 线程池核心容量
     */
    private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
    /**
     * 线程池最大容量
     */
    private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
    /**
     * 过剩的空闲线程的存活时间
     */
    private static final int KEEP_ALIVE = 10;
    /**
     * 队列大小
     */
    private static final int CAPACITY_COUNT = 20;
    /**
     * 在PriorityBlockingQueue传入比较优先级的规则
     */
    private static PriorityBlockingQueue<Runnable> queue = new PriorityBlockingQueue<>(CAPACITY_COUNT, new ComparePriority());
    private static Executor executor = null;

    public static Executor getExecutor() {
        if (executor == null) {
            synchronized (ThreadPoolUtil.class) {
                if (executor == null) {
                    executor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, queue);
                }
            }
        }
        return executor;
    }

    public static abstract class RunWithPriority implements Runnable {
        //优先级大小
        public int priority;

        public RunWithPriority(int priority) {
            this.priority = priority;
        }

        public int getPriority() {
            return priority;
        }
    }

    public static class ComparePriority<T extends RunWithPriority> implements Comparator<T> {

        @Override
        public int compare(T lhs, T rhs) {
            return rhs.getPriority() - lhs.getPriority();
        }
    }
}
